/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.dispatcher;

import com.jspx.txweb.util.TXWebUtil;
import com.jspx.utils.*;
import com.jspx.boot.JspxNetApplication;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: chenYuan
 * Date: 2007-12-20
 * Time: 12:40:51
 * tomcat get 方法需要设置编码修复
 */
public class ServletDispatcher extends HttpServlet implements javax.servlet.Servlet {

    public ServletDispatcher() {

    }

    /**
     * 初始平台
     *
     * @param servletConfig 配置
     * @throws javax.servlet.ServletException 异常
     */
    public void init(ServletConfig servletConfig) throws javax.servlet.ServletException {

        String defaultPath = servletConfig.getServletContext().getInitParameter("defaultPath");
        if (!StringUtil.isNULL(defaultPath))
        {
            JspxNetApplication.autoRun(defaultPath);
        } else {
            String filePath = servletConfig.getServletContext().getRealPath("/");
            if (!StringUtil.isNULL(filePath)) filePath = FileUtil.mendPath(filePath + "WEB-INF/classes");
            if (!StringUtil.isNULL(filePath)&&FileUtil.isDirectory(filePath))
            {
                JspxNetApplication.autoRun(FileUtil.mendPath(filePath));
            }
            else   JspxNetApplication.autoRun();
        }

        String realPath = servletConfig.getServletContext().getInitParameter("realPath");
        if (StringUtil.isNULL(realPath))
            realPath = servletConfig.getServletContext().getRealPath("/");
        Dispatcher.setRealPath(FileUtil.mendPath(realPath));
    }

    /**
     *
     * @param servletRequest  Request  请求
     * @param servletResponse  Response 应答
     * @throws javax.servlet.ServletException  异常
     * @throws java.io.IOException 异常
     */
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        Dispatcher.getInstance().wrapRequest(request, response);

    }

    /**
     * 卸载数据
     */
    public void destroy() {
        JspxNetApplication.destroy();
    }
}